package development.app;

import java.util.Vector;

import state.AlertListener;
import state.Clip;
import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.Sprite;
import state.component.Event;
import state.component.EventListener;
import state.component.GameScrollBar;
import state.component.GridMenu;
import state.component.MultiTab;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.MapDataPackage;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.NumberUtil;
import state.util.array.ByteArray;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.bean.Category;
import development.group.FrmGroupBongDaXoSo;
import development.group.FrmGroupThoiTietTinTuc;

public class FrmSuKienHot extends GameForm implements EventListener, AlertListener {
  public static final int EVENT_CATEGORY_REQUEST = 900;
  public static final int EVENT_CATEGORY_RESPONSE = 901;
  public static final int EVENT_CONTENT_RESQUEST = 902;
  public static final int EVENT_CONTENT_RESPONSE = 903;
  
  private static final int DY = 25;

  private ImageText text8;
  private ImageText text11;
  private int categoryIndex;
  private String type;
  private Hashtable logAction = null;
  private int currentAction;
  private Vector categoriesPath;

  private int dy;
  private int CATEGORY_IMAGE_HEIGHT;
  private final int DEFAULT_TEXT_X = 5;
  private GameScrollBar scrollBar;
  private Clip textView; // Là khung nhìn để vẽ đoạn text ra

  private Vector categories;

  private final String WAITING_MESSAGE = "Xin chờ trong giây lát...";
  private int packageNumber;
  private int totalPackage;
  private int percent;
  
  private GridMenu gridMenu;

  private static GameForm singleton;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmSuKienHot();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    categories = new Vector();
    categoriesPath = new Vector();
    logAction = new Hashtable();
    currentAction = 1;
    type = "category";
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    text11 = FontManager.getFont(FontManager.FONT_SIZE_11);
    CATEGORY_IMAGE_HEIGHT = Global.getDefaultAvatar().getHeight();
    dy = DY;
    
    gridMenu = new GridMenu(_manager, null, null, 1, 0, DrawUtils.getTopBarHeight(), Global.getDefaultAvatar().getHeight() + 5, Global.getDefaultAvatar().getWidth() + 5, this);
    gridMenu.setVisible(false);

    textView = new Clip(DEFAULT_TEXT_X, dy, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - dy - 10); // Là khung nhìn để vẽ đoạn text ra
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);

    Vector value = new Vector();
    value.addElement("SU_KIEN_HOT");
    request(EVENT_CATEGORY_REQUEST, value);
    categoriesPath.addElement("Sự kiện HOT");
    DrawUtils.setBottomBar(_manager, "Menu chính", "Chọn", "Trở về");
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    MapDataPackage mapDataPackage = MapDataPackage.getMapPackage(dataPackage);
    type = mapDataPackage.popString("type");
    if (type.equals("-1")) {
      Global.alert.showAlert2(this, GameAlert.OK_TYPE, "Chưa có dữ liệu cho mục này", -1);
      return;
    }
    GameGlobal.systemCanvas.hideAlert();
    dy = DY;
    Category category = null;
    switch (header) {
    case EVENT_CATEGORY_RESPONSE:
      category = new Category();
      category.id = mapDataPackage.getString("id");
      category.code = mapDataPackage.getString("code");
      category.name = mapDataPackage.getString("name");
      category.hasChild = NumberUtil.parseInt(mapDataPackage.getString("child")) > 0;
      ByteArray btImage = mapDataPackage.getByteArray("avatarImage");
      category.image = GameImage.createImage(btImage, 0, btImage.len());
      CATEGORY_IMAGE_HEIGHT = category.image.getHeight();

      packageNumber = mapDataPackage.getInt("packageNumber");
      totalPackage = mapDataPackage.getInt("totalPackage");
      percent = (packageNumber * 100) / totalPackage;
      categories.addElement(category);
      gridMenu.setHozDistance(category.image.getHeight() + 5);
      gridMenu.setDisplayTitle(false);
      gridMenu.setVisible(true);
      Sprite sprite = new Sprite(null, null, 0, 0, Constants.TOP_LEFT_ANCHOR);
      sprite.setSize(GameConstants.SCREEN_WIDTH - 10, Global.getDefaultAvatar().getHeight() + 5);
      sprite.setId((byte) (categories.size() - 1));
      gridMenu.addSpriteItem(sprite, category.id);
      sprite.setDrawListener(new DrawListener() {
        public void paint(Sprite source, Graphics g) {
          int index = source.getId();
          if (index > categories.size() - 1) {
            return;
          }
          Category category1 = (Category) categories.elementAt(index);
          g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
          if (!category1.hasChild) {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          } else {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          }
          if (categoryIndex == index) {
            g.setColor(0x53A4CF);
            g.fillRect(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH, category1.image.getHeight() + 7);
            g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
            if (!category1.hasChild) {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            } else {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            }
          }
          if (!category1.hasChild) {
            text8.drawString3(g, "Chi tiết >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + 30, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
          }
          g.setColor(0xC0C0C0);
          g.drawLine(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH, source.getRealY() - 7);
          
          if(index == gridMenu.getNumberOfItem() - 1){
            g.setColor(0xC0C0C0);
            g.drawLine(0, source.getRealY() + category1.image.getHeight() + 2, GameConstants.SCREEN_WIDTH, source.getRealY() + category1.image.getHeight() + 2);
          }
        }
      });
      break;
    case EVENT_CONTENT_RESPONSE:
      category = new Category();
      category.id = mapDataPackage.getString("id");
      category.code = mapDataPackage.getString("code");
      category.name = mapDataPackage.getString("name");
      category.hasChild = false;
      category.exParam.addElement(mapDataPackage.getString("value"));
      categories.addElement(category);
      _manager.enableTouchPad();
      break;
    }
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    if (categories.isEmpty()) {
      text8.drawString2(g, WAITING_MESSAGE, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2, GameConstants.TOP_HCENTER_ANCHOR);
    }
    if (type.equals("content")) {
      drawContent(g);
    }

    text8.drawString2(g, GameStringUtils.join(categoriesPath, "-"), GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 5, GameConstants.TOP_HCENTER_ANCHOR);
  }

  private void drawContent(Graphics g) {
    int textY = dy;
    text11.setBold(true);
    for (int i = 0; i < categories.size(); i++) {
      Category category = (Category) categories.elementAt(i);
      textY = text11.drawParagraph2(g, (String) category.exParam.elementAt(0), GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 10, DEFAULT_TEXT_X, textY, scrollBar);
    }
    scrollBar.draw(g);
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.LEFT:
      if (parentGroup instanceof FrmGroupThoiTietTinTuc) {
        FrmGroupThoiTietTinTuc.setTab(1);
      }
      break;
    case Key.DOWN:
      if (!categories.isEmpty()) {
        if (type.equals("category")) {
          if (categoryIndex < categories.size() - 1) {
            categoryIndex++;
          }
        }
      }
      if (type.equals("category")) {
        if (categories.size() * (CATEGORY_IMAGE_HEIGHT + 25) < GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight()) {
          return;
        }
        if (scrollBar.canScrollUp()) {
          dy = dy - (CATEGORY_IMAGE_HEIGHT + 25);
        }
      }
      if (type.equals("content") && scrollBar.canScrollUp()) {
        dy -= 5;
      }
      break;
    case Key.UP:
      if (!categories.isEmpty()) {
        if (categoryIndex > 0) {
          categoryIndex--;
        } else if (categoryIndex == 0) {
        }
      }
      if (type.equals("category")) {
        if (scrollBar.canScrollDown()) {
          dy = dy + (CATEGORY_IMAGE_HEIGHT + 25);
        }
      }
      if (type.equals("content")) {
        if (scrollBar.canScrollDown()) {
          dy += 5;
        } else {
          dy = DY;
        }
      }
      break;
    case Key.FIRE:
      process(gridMenu.getCurrentSelectedIndex());
      break;
    case Key.SOFT_LEFT:
      if (!isLoadingCompleted()) {
        return;
      }
      parentGroup.goBack();
      break;
    case Key.SOFT_RIGHT:
      if (!isLoadingCompleted()) {
        return;
      }
      if (currentAction > 1) {
        if(type.equals("content")){
          _manager.disableTouchPad();
        }
        clearCategory();
        back();
        if (categoriesPath.size() > 0) {
          categoriesPath.removeElementAt(categoriesPath.size() - 1);
        }
      } else {
        parentGroup.goBack();
      }
      break;
    }
  }

  public void keyRepeated(int keyCode) {
    switch (keyCode) {
    case Key.DOWN:
      if (type.equals("content") && scrollBar.canScrollUp()) {
        dy -= 5;
      }
      break;
    case Key.UP:
      if (type.equals("content")) {
        if (scrollBar.canScrollDown()) {
          dy += 5;
        } else {
          dy = DY;
        }
      }
      break;
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == -1) {
      if (currentAction > 1) {
        clearCategory();
        back();
      }
    }
  }

  private boolean isLoadingCompleted() {
    return packageNumber == totalPackage;
  }

  private void back() {
    currentAction--;
    String values = (String) logAction.get(String.valueOf(currentAction));
    StringArray requestParams = GameStringUtils.split(values, ",");
    int request = NumberUtil.parseInt(requestParams.get(0));
    Vector value = new Vector();
    value.addElement(requestParams.get(1));
    request(request, value);
  }

  private void request(int header, Vector parameters) {
    DataPackage dataPackage = DataPackage.createDataPackage1(header);
    for (int i = 0; i < parameters.size(); i++) {
      dataPackage.putString(parameters.elementAt(i).toString());
    }
    Global.appClient.write(dataPackage);
    logAction.put(String.valueOf(currentAction), buildLogAction(header, parameters));
  }

  private String buildLogAction(int requestType, Vector parameters) {
    StringBuffer sb = new StringBuffer();
    sb.append(String.valueOf(requestType));
    sb.append(",");
    for (int i = 0; i < parameters.size(); i++) {
      sb.append(parameters.elementAt(i).toString());
      sb.append(",");
    }
    if (sb.toString().endsWith(",")) {
      sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
  }

  private void clearCategory() {
    gridMenu.clearData();
    categories.removeAllElements();
    categoryIndex = 0;
    Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
  }

  public void onActionPerform(Event event) {
    if (MultiTab.OPEN_TAB_EVENT.equals(event.getAction())) {
      DrawUtils.setBottomBar(_manager, "Menu chính", "Chọn", "Trở về");
      return;
    }
    if (event.getSource() == gridMenu) {
      process(gridMenu.getCurrentSelectedIndex());
    }
  }

  private void process(int index) {
    if (!isLoadingCompleted()) {
      return;
    }
    currentAction++;
    Category category = (Category) categories.elementAt(index);
    if (!categoriesPath.contains(category.name)) {
      categoriesPath.addElement(category.name);
    }
    if (category.code.equals("DAU_GIA_NGUOC")) {
      if (parentGroup instanceof FrmGroupBongDaXoSo) {
        FrmDauGiaNguoc.backTab = this;
        FrmGroupBongDaXoSo frmGroupBongDaXoSo = (FrmGroupBongDaXoSo) FrmGroupBongDaXoSo.instance();
        frmGroupBongDaXoSo.getMultiTab().setTab(2, FrmDauGiaNguoc.instance(), null);
      } else if (parentGroup instanceof  FrmGroupThoiTietTinTuc) {
        FrmDauGiaNguoc.backTab = this;
        FrmGroupThoiTietTinTuc frmGroupThoiTietTinTuc = (FrmGroupThoiTietTinTuc) FrmGroupThoiTietTinTuc.instance();
        frmGroupThoiTietTinTuc.getMultiTab().setTab(2, FrmDauGiaNguoc.instance(), null);
      }
    } else {
      if (type.equals("category")) {
        if (category.hasChild) {
          Vector value = new Vector();
          value.addElement(category.code);
          request(EVENT_CATEGORY_REQUEST, value);
          clearCategory();
        } else {
          Vector value = new Vector();
          value.addElement(category.id);
          request(EVENT_CONTENT_RESQUEST, value);
          clearCategory();
        }
      }
    }
  }

  public void destroy() {
    categoryIndex = 0;
    text8 = null;
    text11 = null;
    type = null;
    logAction = null;
    categoriesPath = null;
    scrollBar = null;
    textView = null;
    categories = null;
    gridMenu = null;
  }
}
